C Loops: For, While, Do While, Looping Statements with Example

 C Loops: For, While, Do While, Looping Statements with Example


A loop allows one to execute a statement or block of statements repeatedly. There are mainly two types of iterations or loops – unbounded iteration or unbounded loop and bounded iteration or bounded loopA loop can either be a pre-test loop or be a post-test loop as illustrated in the diagram.


“While” Construct
Expanded Syntax of “while” and its Flowchart Representation while statement is a pretest loop. The basic syntax of the while statement is shown below: 

 

Example 
#include <stdio.h>                                         
int main()
{
int c;
c=5; // Initialization
while(c>0)
{ // Test Expression
printf(“ \n %d”,c);
c=c-1; // Updating
}
return 0;
}
 
Testing for floating-point ‘equality’
float x;
x = 0.0;
while(x != 1.1)
{
x = x + 0.1;
printf(“1.1 minus %f equals %.20g\n”, x, 1.1 -x);
}
The above loop never terminates on many computers, because 0.1
cannot be accurately represented using binary numbers.
Never test floating point numbers for exact equality, especially in
loops.
The correct way to make the test is to see if the two numbers are

‘approximately equal’. 

“for” Construct
The general form of the for statement is as   
           
follows:
for(initialization; TestExpr; updating)
stmT;
for construct
flow chart 


EXAMPLE
#include <stdio.h>
int main()
{
int n, s=0, r;
printf(“\n Enter the Number”);
scanf(“%d”, &n);
for(;n>0;n/=10)
{
r=n%10;
s=s+r;
}
printf(“\n Sum of digits %d”, s);
return 0;
}


“do-while” Construct 
The C do-while loop
The form of this loop
construct is as
follows:
do
{
stmT; /* body of
statements would be
placed here*/
}while(TestExpr)



Example - do loop 
// Program to add numbers until user enters zero
#include <stdio.h>
int main()
{ double number, sum = 0;
// loop body is executed at least once
do
{ printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);
printf("Sum = %.2lf",sum);
return 0;

Point to Note 
With a do-while statement, the body of the loop is executed first and the test expression is checked after the loop body is executed. Thus, the do-while statement always executes the loop body at least once. 

Which loop should be used??? 
When to use which loop

For, while loops are pre test loops. Do while is
post test loop.

For loop is usually when the number of iterations
are known in advance. Like o to 75 etc.

While and do while are for unknown iterations.

While – when you don’t even want to execute the
body even once.

Do – while when you want to execute the body 


Hope you guys understand the concept of loops in C and I tried my best to explain C Loops: For, While, Do While, Looping Statements with Example

You can Practice question on this Topic in Practice and Learn section on Menu Bar with questions and their answers ..Kindly check out there.


Previous
Next Post »